/**
 * Created by jyd on 2017/7/22.
 * 数字格式化 金钱
 * * 参数说明：
 * number：要格式化的数字
 * prec：保留几位小数
 * dec：小数点符号
 * sep：千分位符号
 * roundtag:舍入参数，默认 "ceil" 向上取,"floor"向下取,"round" 四舍五入
 */

const accounting = function (number, prec = 2, dec = '.', sep = ',', roundtag = 'round') {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  const n = !isFinite(+number) ? 0 : +number
  let s = ''
  accounting.toFixedFix(n, prec, roundtag)
  s = (prec ? accounting.toFixedFix(n, prec, roundtag) : '' + Math.round(n)).split('.')
  const re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}

accounting.toFixedFix = function (n, prec, roundtag) {
  const k = Math.pow(10, prec)
  return '' + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)) / k
}

export default accounting
